package com.svtar.ywg.api;

import android.content.Context;

import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.request.base.Request;
import com.svtar.ywg.R;
import com.svtar.ywg.ui.view.LoadingDailog;

/**
 * 请求回调简单封装
 */
public abstract class SimpleCallback extends AbsCallback<String> {

    private StringConvert convert;

    private LoadingDailog loadingDailog;

    private Context mContext;

    private boolean showDailog = true;

    private SimpleCallback() {

    }

    public SimpleCallback(Context context) {
        this.mContext = context;
        convert = new StringConvert();
    }

    /**
     * @param context
     * @param showDailog 是否显示加载Dailog
     */
    public SimpleCallback(Context context, boolean showDailog) {
        this.mContext = context;
        this.showDailog = showDailog;
        convert = new StringConvert();
    }

    @Override
    public void onStart(Request request) {
        super.onStart(request);
        if (showDailog) {
            loadingDailog = new LoadingDailog.Builder(mContext)
                    .setCancelable(true)
                    .setCancelOutside(true)
                    .setMessage(mContext.getResources().getString(R.string.loadinging))
                    .create();
            loadingDailog.show();
        }
    }

    @Override
    public void onFinish() {
        super.onFinish();
        if (showDailog && loadingDailog != null) {
            loadingDailog.dismiss();
        }
    }

    @Override
    public String convertResponse(okhttp3.Response response) throws Throwable {
        String s = convert.convertResponse(response);
        response.close();
        return s;
    }
}
